package com.towexin.application.websocket.controller;

import com.towexin.application.websocket.domain.MessageBody;
import com.towexin.utils.ComTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Date;

/**
 * TODO
 *
 * @author Towexin
 * @version 1.0
 * @date 2021/8/11 11:49
 */
@RestController
public class MessageController {

    @Autowired
    private SimpMessageSendingOperations simpMessageSendingOperations;

    /**
     * 点对点发送消息，将消息发送到指定用户
     */
    @MessageMapping("to-user")
    public void sendUserMessage(Principal principal, MessageBody messageBody) {
        messageBody.setFrom(principal.getName());
        messageBody.setTimestamp(new Date().getTime());
        messageBody.setDateString(ComTool.getDate("yyyy.MM.dd HH:mm:ss"));
        // 目标接收人、目标订阅的频道、消息实体
        simpMessageSendingOperations.convertAndSendToUser(messageBody.getTargetUser(), messageBody.getDestination(), messageBody);
    }

    @MessageMapping("chatroom")
    public void sendChatroomMessage(Principal principal, MessageBody messageBody){
        messageBody.setFrom(principal.getName());
        messageBody.setTimestamp(new Date().getTime());
        messageBody.setDateString(ComTool.getDate("yyyy.MM.dd HH:mm:ss"));
        // 订阅的频道、消息实体
        simpMessageSendingOperations.convertAndSend(messageBody.getDestination(), messageBody);
    }
}
